package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class TcpEchoClient {
    private Socket socket=null;
    public TcpEchoClient(String serverIp,int serverPort) throws IOException {
        socket=new Socket(serverIp, serverPort);
    }

    public void start(){
        System.out.println("客户端已启动");
        Scanner scanner=new Scanner(System.in);
        try(InputStream inputStream=socket.getInputStream();
            OutputStream outputStream= socket.getOutputStream()){
            //为了方便使用套壳操作
            Scanner scannerNet=new Scanner(inputStream);
            PrintWriter writer=new PrintWriter(outputStream);
            while(true){
                //从控制台上读取数据
                String resquest=scanner.next();
                //发送到服务器
                writer.println(resquest);
                //加上刷新缓冲区操作 才是真正发送数据
                writer.flush();
                //读取服务器返回的响应
                String response=scannerNet.next();
                //打印到控制台上
                System.out.println(response);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient client=new TcpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
